import { api } from 'dicomweb-client'
import { PACS_SETTING } from '@/config/config'
import cornerstoneDICOMImageLoader from '@cornerstonejs/dicom-image-loader'

export default async function createImageIdsAndCacheMetaDataTest({
                                                               StudyInstanceUID,
                                                               SeriesInstanceUID,
                                                               SOPInstanceUID = null,
                                                               wadoRsRoot,
                                                               client = null
                                                             }) {
  const studySearchOptions = {
    studyInstanceUID: StudyInstanceUID,
    seriesInstanceUID: SeriesInstanceUID
  }
  client = client || new api.DICOMwebClient({
      url: wadoRsRoot,
      headers: PACS_SETTING.OpenAuth ? {
        'Authorization': 'Basic ' + btoa(PACS_SETTING.username + ':' + PACS_SETTING.password)
      } : {}
    }
  )
  const SOP_INSTANCE_UID = '00080018'
  const SERIES_INSTANCE_UID = '0020000E'
  const MODALITY = '00080060'
  let instances = await client.retrieveSeriesMetadata(studySearchOptions)
  let imageIds = instances.map((instanceMetaData) => {
    const SeriesInstanceUID = instanceMetaData[SERIES_INSTANCE_UID].Value[0]
    const SOPInstanceUIDToUse =
      SOPInstanceUID || instanceMetaData[SOP_INSTANCE_UID].Value[0]
    const prefix = 'wadors:'

    const imageId =
      prefix +
      wadoRsRoot +
      '/studies/' +
      StudyInstanceUID +
      '/series/' +
      SeriesInstanceUID +
      '/instances/' +
      SOPInstanceUIDToUse +
      '/frames/1'

    cornerstoneDICOMImageLoader.wadors.metaDataManager.add(
      imageId,
      instanceMetaData
    )
    return imageId
  })
  return imageIds
}
